const treeData = require("./treeData");
const { clone } = require("../cloneDeep");
/**
 *  @description 递归实现
 *  @description 如果层级很深，会爆栈
 *  @param {any[]} arr
 */
function depthLoop(arr, result = []) {
  arr.forEach((item) => {
    const res = clone(item);
    Reflect.deleteProperty(res, "children");
    result.push(res);
    if (item.children && item.children.length) {
      return depthLoop(item.children, result);
    }
  });
  return result;
}
// const nodes = depthLoop(treeData);
// console.log(nodes, "nodes");

/**
 *  @description 通过栈来实现
 *  @description 实现：通过维护一个栈，不断的从栈中取出元素，把取出的元素的子节点放入栈中，放到栈的最前面
 *  @param {any[]} arr
 */
function depthStackLoop(arr) {
  const tree = clone(arr);
  const result = [];
  while (tree.length > 0) {
    const node = tree.shift();
    result.push(node.name);
    if (node.children && node.children.length) {
      tree.unshift(...node.children);
    }
  }
  return result;
}

const nodesCopy = depthStackLoop(treeData);
console.log(nodesCopy, "nodes");
